package com.woniu.controller;

import com.woniu.service.EmaillServicec;
import com.woniu.util.ResponseEnum;
import com.woniu.util.ResponseUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("/email")
public class EmailController {
@Resource
private EmaillServicec emailService;
    /**
     * 接收前端订阅请求
     * @param email 前端传递的邮箱（JSON格式：{"email":"xxx@xx.com"}）
     * @return 响应结果（含是否新订阅、提示信息）
     */
    @PostMapping("/subscribe")
    public ResponseUtil subscribe(@RequestBody Map<String, String> email) {
        String s = email.get("email");
        //判断空
        if (s == null || s.equals("")) {
            return ResponseUtil.get(ResponseEnum.FAIL);

        }
        String emailLow = s.trim().toLowerCase();//统一转小写
        //判断是否订阅 redis set去重
        boolean emailSubscribed = emailService.isEmailSubscribed(emailLow);
        if (emailSubscribed) {
            return ResponseUtil.get(ResponseEnum.EMAILL_EXIST);
        }
        //存redis
        emailService.addNewSubscribeEmail(emailLow);
        return ResponseUtil.get(ResponseEnum.EMAILL_SUCCESS);

    }
}
